package LunaServer.email;

import java.util.Properties;
import java.util.Random;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * 邮件服务类，用于发送验证码等邮件功能
 */
public class EmailService {
    private String smtpHost;
    private String smtpPort;
    private String username;
    private String password;
    private String fromAddress;
    
    /**
     * 构造函数
     * @param smtpHost SMTP服务器地址
     * @param smtpPort SMTP服务器端口
     * @param username 邮箱用户名
     * @param password 邮箱密码或授权码，一般为API Key。
     * @param fromAddress 发件人地址
     */
    public EmailService(String smtpHost, String smtpPort, String username, String password, String fromAddress) {
        this.smtpHost = smtpHost;
        this.smtpPort = smtpPort;
        this.username = username;
        this.password = password;
        this.fromAddress = fromAddress;
    }
    
    /**
     * 生成随机验证码
     * @param length 验证码长度
     * @return 随机验证码
     */
    public String generateVerificationCode(int length) {
        String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        for (int i = 0; i < length; i++) {
            code.append(characters.charAt(random.nextInt(characters.length())));
        }
        
        return code.toString();
    }
    
    /**
     * 发送验证码邮件
     * @param toAddress 收件人地址
     * @param verificationCode 验证码
     * @return 发送是否成功
     */
    public boolean sendVerificationCode(String toAddress, String verificationCode) {
        try {
            // 设置邮件服务器属性
            Properties props = new Properties();
            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", smtpPort);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密
            
            // 创建认证器
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            };
            
            // 创建会话
            Session session = Session.getInstance(props, authenticator);
            
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
            message.setSubject("注册验证码");
            
            String content = "您的注册验证码是: " + verificationCode + "\n\n验证码有效期为10分钟，请尽快完成注册。";
            message.setText(content);
            
            // 发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}